﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Get", "AXNodeChildItem")]
    public class Get_AXNodeChildItem : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Path = "\\";

        [System.Management.Automation.Parameter(Mandatory = false)]
        public System.Management.Automation.SwitchParameter Recurse = false;

        protected override void ProcessRecord()
        {
            var ax_session = Microsoft.Dynamics.Framework.Portal.SessionHelper.Instance.GetSession();
            var node = Proxy.TreeNode.findNode(ax_session.AxaptaAdapter, Path);
            if (this.Recurse == false)
            {
                var iter = node.AOTiterator();
                foreach (var childnode in iter.AsEnumerable())
                {
                    this.WriteObject(childnode.AOTname());
                }
            }
            else
            {
                this.recurse(node, this.Path);
            }
        }

        private void recurse(Proxy.TreeNode node, string path)
        {
            this.WriteObject(path);
            foreach (var cn in node.AOTiterator().AsEnumerable())
            {
                recurse(cn, path + "\\" + cn.AOTname());
            }
        }
    }

}